package model

import (
	"gowork/courseSelection/utils"
	"strconv"
	"sync"
	"time"
)

type CourseArrangement struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	TeacherId int64
	TeacherName string
	Week string
	Class string
	TimeSlot string
	Cridit int
	Duration string
	Cycle string
	Type int
	SumPeople int
	CurrentNumber int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ClassScheduleCard struct {
	Id int64 `xorm:"pk autoincr"`
	StudentId int64
	StudentName string
	CourseId int64
	CourseName string
	TeacherId int64
	TeacherName string
	Week string
	Class string
	TimeSlot string
	Cridit int
	Duration string
	Cycle string
	Type int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type WhatWeek struct {
	Name string
	ClassList []*WhatClass
}

type WhatClass struct {
	Name string
	ClassCard ClassScheduleCard
}

func (CourseArrangement *CourseArrangement)CreateCourse(ca *CourseArrangement)(map[string]interface{}, error){

	w := new(utils.Worker)
	ca.Id = w.GetId()
	ca.CreatedAt = time.Now()
	ca.UpdatedAt = time.Now()

	x.Insert(ca)

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

var lock sync.Mutex

func (whatWeek *WhatWeek)SelectClass(sId int64, ca *CourseArrangement)(map[string]interface{}, error){

	lock.Lock()

	lca := new(CourseArrangement)
	x.Id(ca.Id).Get(lca)
	if lca.SumPeople < lca.CurrentNumber + 1{

		lock.Unlock()

		return map[string]interface{}{"code":400, "message":"该课程预约已满"}, nil
	}

	w := new(utils.Worker)

	var csc = ClassScheduleCard{
		Id:          w.GetId(),
		StudentId:   sId,
		CourseId:    ca.Id,
		CourseName:  ca.Name,
		TeacherId:   ca.TeacherId,
		TeacherName: ca.TeacherName,
		Week:        ca.Week,
		Class:       ca.Class,
		TimeSlot:    ca.TimeSlot,
		Cridit:      ca.Cridit,
		Duration:    ca.Duration,
		Cycle:       ca.Cycle,
		Type:        ca.Type,
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}
	x.Insert(&csc)

	nca := new(CourseArrangement)
	x.Id(ca.Id).Get(nca)
	nca.CurrentNumber += 1
	x.Id(ca.Id).Update(nca)

	lock.Unlock()

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

func (whatWeek *WhatWeek)QueryClassCard(sId int64)([]*WhatWeek, error){

	var  wwList []*WhatWeek
	for i:=1; i<=7; i++{
		iStr := strconv.Itoa(i)
		var ww = WhatWeek{
			Name:      "星期" + iStr,
		}
		wwList = append(wwList, &ww)
	}

	for _, wwv := range wwList{
		for j:=1; j<=11; j++ {
			jStr := strconv.Itoa(j)
			var wc = WhatClass{
				Name: jStr,
			}
			wwv.ClassList = append(wwv.ClassList, &wc)
		}

		for _, wcv := range wwv.ClassList{
			x.Where("week = ?", wwv.Name).And("class = ?", wcv.Name).And("student_id = ?", sId).Get(&wcv.ClassCard)
		}
	}

	return wwList, nil
}

